package com.henghe.frame.domain.base;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.henghe.frame.common.entity.JsonDataResult;
import com.henghe.frame.common.entity.JsonPageResult;
import com.henghe.frame.common.entity.JsonResult;
import com.henghe.frame.common.entity.TableDataInfo;
import com.henghe.frame.common.util.LogUtil;
import com.henghe.frame.common.util.ServletUtils;
import com.henghe.frame.common.util.StringUtils;
import com.henghe.frame.domain.entity.PageDomain;
import com.henghe.frame.domain.entity.TableSupport;
import com.henghe.frame.domain.util.SqlUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.*;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/16 15:49
 */
@Slf4j
public class BaseClass {

    @Autowired
    public LogUtil logUtil;
    @Autowired(required = false)
    private HttpServletRequest request;

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @SneakyThrows
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    public void handleLog(Object... args) {
        logUtil.handleRequest(args);
    }

    /**
     * 设置请求分页数据
     */
    public void startPage() {
        if (request != null) {
            if (request.getMethod().equals("GET")) {
                PageDomain pageDomain = TableSupport.buildPageRequest();
                Integer pageIndex = pageDomain.getPageIndex();
                Integer pageSize = pageDomain.getPageSize();
                if (StringUtils.isNotNull(pageIndex) && StringUtils.isNotNull(pageSize)) {
                    String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
                    if (StringUtils.isEmpty(orderBy)) {
                        PageHelper.startPage(pageIndex, pageSize);
                    } else {
                        PageHelper.startPage(pageIndex, pageSize, orderBy);
                    }
                }
            } else {
                String body = ServletUtils.getBody(request);
                if (StringUtils.isEmpty(body))
                    return;
                JSONObject jo = JSONObject.parseObject(body);
                Integer pageIndex = jo.getInteger("page_index");
                Integer pageSize = jo.getInteger("page_size");
                if (StringUtils.isNotNull(pageIndex) && StringUtils.isNotNull(pageSize)) {
                    String orderBy = SqlUtil.escapeOrderBySql(jo.getString("order_by"));
                    if (StringUtils.isEmpty(orderBy)) {
                        PageHelper.startPage(pageIndex, pageSize);
                    } else {
                        PageHelper.startPage(pageIndex, pageSize, orderBy);
                    }
                }
            }
        }
    }

    public Map<String, Integer> getRequestBodyPageParam() {
        if (request != null) {
            Map<String, Integer> paramMap = new HashMap<>();
            if (request.getMethod().equals("GET")) {
                PageDomain pageDomain = TableSupport.buildPageRequest();
                Integer pageIndex = pageDomain.getPageIndex();
                Integer pageSize = pageDomain.getPageSize();
                if (StringUtils.isNotNull(pageIndex) && StringUtils.isNotNull(pageSize)) {
                    paramMap.put("pageIndex", pageIndex);
                    paramMap.put("pageSize", pageSize);
                    return paramMap;
                }
                return null;
            } else {
                String body = ServletUtils.getBody(request);
                if (StringUtils.isEmpty(body)) {
                    return null;
                }
                JSONObject jo = JSONObject.parseObject(body);
                Integer pageIndex = jo.getInteger("page_index");
                Integer pageSize = jo.getInteger("page_size");
                if (StringUtils.isNotNull(pageIndex) && StringUtils.isNotNull(pageSize)) {
                    paramMap.put("pageIndex", pageIndex);
                    paramMap.put("pageSize", pageSize);
                    return paramMap;
                }
                return null;
            }
        }
        return null;
    }

    public void startPage(String orderByIn) {
        if (request != null) {
            if (request.getMethod().equals("GET")) {
                PageDomain pageDomain = TableSupport.buildPageRequest();
                Integer pageIndex = pageDomain.getPageIndex();
                Integer pageSize = pageDomain.getPageSize();
                if (StringUtils.isNotNull(pageIndex) && StringUtils.isNotNull(pageSize)) {
                    if (StringUtils.isEmpty(orderByIn)) {
                        PageHelper.startPage(pageIndex, pageSize);
                    } else {
                        PageHelper.startPage(pageIndex, pageSize, orderByIn);
                    }
                }
            } else {
                String body = ServletUtils.getBody(request);
                if (StringUtils.isEmpty(body)) {
                    return;
                }
                JSONObject jo = JSONObject.parseObject(body);
                Integer pageIndex = jo.getInteger("page_index");
                Integer pageSize = jo.getInteger("page_size");
                if (StringUtils.isNotNull(pageIndex) && StringUtils.isNotNull(pageSize)) {
//                    String orderBy = SqlUtil.escapeOrderBySql(jo.getString("order_by"));
                    if (StringUtils.isEmpty(orderByIn)) {
                        PageHelper.startPage(pageIndex, pageSize);
                    } else {
                        PageHelper.startPage(pageIndex, pageSize, orderByIn);
                    }
                }
            }
        }

    }

    /**
     * 响应请求分页
     *
     * @param list
     * @return
     */
    public <T> TableDataInfo<T> getDataTable(List<T> list) {
        JsonPageResult<T> jsonPageResult = new JsonPageResult<>();
        PageInfo pageInfo = new PageInfo(list);
        jsonPageResult.setRecords(list);
        jsonPageResult.setCurrentRecords(list.size());
        jsonPageResult.setTotalRecord(pageInfo.getTotal());
        jsonPageResult.setTotalPage(pageInfo.getPages());
        TableDataInfo<T> jsonResult = new TableDataInfo<>();
        jsonResult.setData(jsonPageResult);
        jsonResult.setCode(600);
        jsonResult.setMsg("查询成功");
        return jsonResult;
    }

    public <T> JsonResult<T> succListMsg(List<T> list) {
        JsonPageResult<T> jsonPageResult = new JsonPageResult<>();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(600);
        jsonResult.setMsg("查询成功");
        jsonPageResult.setRecords(list);
        jsonResult.setData(jsonPageResult);
        return jsonResult;
    }

    public <T> JsonResult<T> succListMsg(List<T> list,Object exData) {
        JsonPageResult<T> jsonPageResult = new JsonPageResult<>();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(600);
        jsonResult.setMsg("查询成功");
        jsonPageResult.setRecords(list);
        jsonPageResult.setExData(exData);
        jsonResult.setData(jsonPageResult);
        return jsonResult;
    }

    public <T> TableDataInfo<T> getDataTable(List<T> list, Object exData) {
        JsonPageResult<T> jsonPageResult = new JsonPageResult<>();
        PageInfo pageInfo = new PageInfo(list);
        jsonPageResult.setRecords(list);
        jsonPageResult.setCurrentRecords(list.size());
        jsonPageResult.setTotalRecord(pageInfo.getTotal());
        jsonPageResult.setTotalPage(pageInfo.getPages());
        jsonPageResult.setExData(exData);
        TableDataInfo<T> jsonResult = new TableDataInfo<>();
        jsonResult.setData(jsonPageResult);
        jsonResult.setCode(600);
        jsonResult.setMsg("查询成功");
        return jsonResult;
    }

    protected <T> JsonResult<T> message(Integer code, String msg, T data) {
        JsonResult<T> jsonResult = new JsonResult();
        jsonResult.setCode(code);
        jsonResult.setMsg(msg);
        if (Objects.nonNull(data)) {
            JsonDataResult<T> jsonDataResult = new JsonDataResult<>();
            if (data instanceof List ||
                    data instanceof Set) {
                jsonDataResult.setRecords(data);
            } else {
                jsonDataResult.setData(data);
            }
            jsonResult.setData(jsonDataResult);
        }
        return jsonResult;
    }

    protected <T> JsonResult<T> message(Integer code, String msg, T data, Object exData) {
        JsonResult<T> jsonResult = new JsonResult();
        jsonResult.setCode(code);
        jsonResult.setMsg(msg);
        if (Objects.nonNull(data)) {
            JsonDataResult<T> jsonDataResult = new JsonDataResult<>();
            if (data instanceof List ||
                    data instanceof Set) {
                jsonDataResult.setRecords(data);
            } else {
                jsonDataResult.setData(data);
            }
            jsonResult.setData(jsonDataResult);
        } else if (Objects.nonNull(exData)) {
            JsonDataResult<T> jsonDataResult = new JsonDataResult<>();
            jsonDataResult.setExData(exData);
            jsonResult.setData(jsonDataResult);
        }
        return jsonResult;
    }

    protected <T> JsonResult<T> succMsg(String msg, T data) {
        return this.message(CommonConstant.SUCCESSED_FLAG, msg, data);
    }

    protected <T> JsonResult<T> succMsg(String msg) {
        return this.succMsg(msg, null);
    }

    protected <T> JsonResult<T> succMsgData(T data) {
        return this.succMsg(CommonConstant.SUCCESSED_MSG, data);
    }

    protected <T> JsonResult<T> succMsg() {
        return this.succMsg(CommonConstant.SUCCESSED_MSG);
    }

    protected <T> JsonResult<T> failMsg(Integer code, String message, T data) {
        return this.message(code, message, data);
    }

    protected <T> JsonResult<T> failMsg(String message) {
        return this.failMsg(CommonConstant.FAILED_FLAG, message, null);
    }

    protected <T> JsonResult<T> failMsg() {
        return this.failMsg(CommonConstant.FAILED_MSG);
    }

    protected <T> JsonResult<T> failMsgData(T data) {
        return this.message(CommonConstant.FAILED_FLAG, CommonConstant.FAILED_MSG, data);
    }

    protected <T> JsonResult<T> failParamMsg() {
        return this.failMsg("参数错误");
    }

    protected <T> JsonResult<T> failRPC() {
        return this.failMsg("远程调用服务异常");
    }

    protected String objToStr(Object res) {
        return res.toString();
    }

    /**
     * @param s 字符串对象
     * @Author: Yi
     * @Return : java.lang.Boolean
     * @Description 判断String是否为空字符串
     */
    protected static Boolean checkStringEmpty(String s) {
        return !org.springframework.util.StringUtils.hasText(s);
    }

    /**
     * @param i 整数对象
     * @Author: Yi
     * @Return : java.lang.Boolean
     * @Description 判断Integer是否为空
     */
    protected static Boolean checkIntegerEmpty(Integer i) {
        return i == null ? true : false;
    }

    /**
     * @param i 整数对象
     * @Author: Yi
     * @Return : java.lang.Boolean
     * @Description 判断Integer是否正数数值(不包含0)
     */
    protected static Boolean checkIntegerGtZero(Integer i) {
        return (i != null && i.compareTo(0) > 0) ? true : false;
    }

    /**
     * @param l List集合
     * @Author: Yi
     * @Return : java.lang.Boolean
     * @Description 判断List是否为空
     */
    protected static <T> Boolean checkListEmpty(Collection<T> l) {
        return CollectionUtils.isEmpty(l);
    }

    /**
     * @param obj
     * @Description 单一元素转集合List
     * @Return : java.util.List<T>
     * @Author: Yi
     * @Date: 15:18 2022/11/7
     */
    protected static <T> List<T> initSingleList(T obj) {
        return new ArrayList<T>() {{
            add(obj);
        }};
    }

    /**
     * @param obj
     * @Description 单一元素转集合Set
     * @Return : java.util.List<T>
     * @Author: Yi
     * @Date: 15:18 2022/11/7
     */
    protected static <T> Set<T> initSingleSet(T obj) {
        return new HashSet<T>() {{
            add(obj);
        }};
    }

}
